package ai-eyes  // 

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.yourcompany.aieyes.databinding.ActivityMainBinding
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.ByteArrayOutputStream
import java.util.concurrent.Executors

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private var imageCapture: ImageCapture? = null
    private var isStreaming = false
    private val executor = Executors.newSingleThreadExecutor()
    private val audioPlayer = AudioPlayer()

    // ⚠️ 替换为你的后端地址（必须 HTTPS）
    private val BASE_URL = "https://your-backend.com/"  // ← ← ← 修改这里！

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        if (allPermissionsGranted()) {
            startCamera()
        } else {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.CAMERA),
                REQUEST_CODE_PERMISSIONS
            )
        }

        binding.btnStart.setOnClickListener { startStreaming() }
        binding.btnStop.setOnClickListener { stopStreaming() }
    }

    private fun startCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener({
            try {
                val cameraProvider = cameraProviderFuture.get()
                bindPreview(cameraProvider)
            } catch (e: Exception) {
                showError("摄像头初始化失败")
            }
        }, ContextCompat.getMainExecutor(this))
    }

    private fun bindPreview(cameraProvider: ProcessCameraProvider) {
        val preview = Preview.Builder().build().also {
            it.setSurfaceProvider(binding.previewView.surfaceProvider)
        }

        imageCapture = ImageCapture.Builder()
            .setTargetRotation(binding.previewView.display.rotation)
            .build()

        val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

        try {
            cameraProvider.unbindAll()
            cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture)
        } catch (e: Exception) {
            showError("无法绑定摄像头")
        }
    }

    private fun startStreaming() {
        isStreaming = true
        binding.btnStart.isEnabled = false
        binding.btnStop.isEnabled = true
        binding.statusText.text = "▶ AI 正在观察世界..."
        analyzeLoop()
    }

    private fun analyzeLoop() {
        if (!isStreaming) return

        captureAndAnalyze()

        binding.root.postDelayed({ analyzeLoop() }, 3000)
    }

    private fun captureAndAnalyze() {
        imageCapture?.takePicture(
            executor,
            object : ImageCapture.OnImageCapturedCallback() {
                override fun onCaptureSuccess(image: ImageProxy) {
                    val buffer = image.planes[0].buffer
                    val bytes = ByteArray(buffer.capacity())
                    buffer.get(bytes)
                    image.close()

                    // 转为 JPEG（简化处理）
                    // 实际项目建议用 ImageUtil 转 YUV to JPEG
                    sendImageToApi(bytes)
                }

                override fun onError(exception: ImageCaptureException) {
                    runOnUiThread {
                        showError("截图失败")
                    }
                }
            }
        )
    }

    private fun sendImageToApi(imageBytes: ByteArray) {
        runOnUiThread {
            binding.statusText.text = "📤 正在分析画面..."
        }

        val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val apiService = retrofit.create(ApiService::class.java)

        val requestBody = imageBytes.toRequestBody("image/jpeg".toMediaType())
        val body = MultipartBody.Part.createFormData("image", "frame.jpg", requestBody)

        apiService.analyzeImage(body).enqueue(object : retrofit2.Callback<ApiResponse> {
            override fun onResponse(call: retrofit2.Call<ApiResponse>, response: retrofit2.Response<ApiResponse>) {
                if (response.isSuccessful && response.body()?.success == true) {
                    val result = response.body()!!
                    runOnUiThread {
                        binding.resultText.text = result.text
                        binding.resultText.visibility = android.view.View.VISIBLE
                        binding.statusText.text = "✅ 描述已生成"

                        result.audio_url?.let { url ->
                            audioPlayer.playAudio(url) {
                                runOnUiThread {
                                    binding.statusText.text = "🔊 语音播放完成"
                                }
                            }
                        }
                    }
                } else {
                    runOnUiThread {
                        showError("AI 分析失败")
                    }
                }
            }

            override fun onFailure(call: retrofit2.Call<ApiResponse>, t: Throwable) {
                Log.e("API", "请求失败", t)
                runOnUiThread {
                    showError("网络错误，请检查连接")
                }
            }
        })
    }

    private fun stopStreaming() {
        isStreaming = false
        audioPlayer.stop()
        binding.btnStart.isEnabled = true
        binding.btnStop.isEnabled = false
        binding.statusText.text = "⏹ 已停止识别"
    }

    private fun showError(message: String) {
        runOnUiThread {
            binding.statusText.text = "❌ $message"
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            if (allPermissionsGranted()) {
                startCamera()
            } else {
                Toast.makeText(this, "需要摄像头权限才能使用", Toast.LENGTH_LONG).show()
                finish()
            }
        }
    }

    private fun allPermissionsGranted() = ContextCompat.checkSelfPermission(
        this,
        Manifest.permission.CAMERA
    ) == PackageManager.PERMISSION_GRANTED

    override fun onDestroy() {
        super.onDestroy()
        audioPlayer.stop()
        executor.shutdown()
    }

    companion object {
        private const val REQUEST_CODE_PERMISSIONS = 10
    }
}